package convert

import (
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
)

func libreOfficeToPdf(libreOffice, fileSrcPath, fileOutDir string) (outFile string, err error) {
	return command(libreOffice, fileSrcPath, fileOutDir, "pdf")
}

func command(libreOffice, inFile, outDir, converterType string) (outFile string, err error) {
	srcFile, err := os.Open(inFile)
	if err != nil && os.IsNotExist(err) {
		return outFile, err
	}

	defer func() {
		_ = srcFile.Close()
	}()

	// 输出文件地址
	outFile = filepath.Join(outDir, strings.Split(path.Base(inFile), ".")[0]+"."+converterType)

	// 执行转换命令
	cmd := exec.Command(libreOffice, "--invisible", "--convert-to", converterType, inFile, "--outdir", outDir)
	return outFile, cmd.Run()
}
